package com.test.chapter4;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

import java.io.*;

/**
 * Chapter04 JUnit测试框架
 */
public class FileReaderTester extends TestCase {

	private FileReader _input;

	public FileReaderTester(String method) {
		super(method);
	}

	@Override
	protected void setUp() throws Exception {
		try {
			_input = new FileReader("data.txt");
		} catch (FileNotFoundException e) {
			throw new RuntimeException("unable to open test file.");
		}
	}

	@Override
	protected void tearDown() throws Exception {
		try {
			_input.close();
		} catch (IOException e) {
			throw new RuntimeException("error on closing test file.");
		}
	}

	public void testRead() throws IOException {
		char ch = '&';
		for (int i = 0; i < 4; i ++)
			ch = (char) _input.read();
		// 断言
		// assert ('d' == ch); // 第4个字符

		// 断言 本来此处的ch值应为d，此表达式false
		// 在书中说这里能显示一个错误信息，可我这里没有。应该是需要手动要打开断言
		//assert ('2' == ch);

		TestCase.assertEquals('d', ch);
		//assertEquals('2', ch); // 报错
	}

	public void testReadBoundaries() throws IOException {
		TestCase.assertEquals("read first char", 'B', _input.read()); // 第一个字母是“B”
		int ch;
		for (int i = 0; i < 222; i++)
			ch =  _input.read();

		//assertEquals("read last char", 6, _input.read());   // 报错
		TestCase.assertEquals("read first char", -1, _input.read()); // 读到最后是 -1
	}

	public void testEmptyRead() throws IOException {
		File empty = new File("empty.txt");
		FileOutputStream out = new FileOutputStream(empty);
		out.close();
		FileReader in  = new FileReader(empty);
		TestCase.assertEquals(-1, in.read());
	}

	public void testReadAfterClose() throws IOException {
		_input.close();
		try {
			_input.read();
			TestCase.fail("no exception for read past end");
		} catch (IOException e) {

		}
	}

	public static Test suite() {
		TestSuite suite = new TestSuite();
		//suite.addTest(new FileReaderTester("testRead"));
		suite.addTest(new FileReaderTester("testReadBoundaries"));
		return suite;
	}

	// 配置 Working directory 为本测试文件路径
	public static void main(String[] args) {
		//junit.textui.TestRunner.run(suite());
		junit.textui.TestRunner.run(new TestSuite(FileReaderTester.class));
	}
}